

package com.example.myproject.controller;


import com.example.myproject.model.Function;
import com.example.myproject.service.FunctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
import java.util.Set;

@RestController
@RequestMapping("/function")
public class FunctionController {

    private final FunctionService functionService;

    @Autowired
    public FunctionController(FunctionService functionService) {
        this.functionService = functionService;
    }

    @GetMapping("/{id}")
    public Optional<Function> getFunctionById(@PathVariable int id) {
        return functionService.findById(id);
    }

    @PostMapping
    public Function createFunction(@RequestBody Function function) {
        return functionService.save(function);
    }

    @PutMapping("/{id}")
    public Function updateFunction(@PathVariable int id, @RequestBody Function functionDetails) {
        Optional<Function> optionalFunction = functionService.findById(id);
        if (optionalFunction.isPresent()) {
            Function function = optionalFunction.get();
            function.setNum(functionDetails.getNum());
            function.setName(functionDetails.getName());
            function.setUrl(functionDetails.getUrl());
            function.setDescription(functionDetails.getDescription());
            function.setStatus(functionDetails.getStatus());
            return functionService.save(function);
        } else {
            // Handle function not found error
            return null;
        }
    }

    @DeleteMapping("/{id}")
    public void deleteFunction(@PathVariable int id) {
        functionService.deleteById(id);
    }

    @PostMapping("/batch")
    public Set<Function> getFunctionsByIds(@RequestBody Set<Long> ids) {
        return functionService.findFunctionsByIds(ids);
    }
}
